package com.xbjtech.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.xbjtech.mapper.RoleMapper;
import com.xbjtech.mapper.RoleResourceMapper;
import com.xbjtech.model.Role;
import com.xbjtech.model.RoleExample;
import com.xbjtech.model.RoleResource;
import com.xbjtech.model.RoleResourceExample;
import com.xbjtech.model.RoleResourceExample.Criteria;
import com.xbjtech.model.vo.RoleVO;
import com.xbjtech.service.RoleService;

/**
* @author sparkCat E-mail:2925365275@qq.com
* @version 创建时间：2019年2月9日 下午7:42:13
* 类说明
*/
@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private RoleResourceMapper roleResourceMapper;
	
	@Override
	public List<RoleVO> list(RoleExample example, Integer page, Integer rows) {
		List<RoleVO> roleVOList = new ArrayList<>();
		List<Role> roles = roleMapper.selectByExampleWithBLOBs(example);
		List<RoleResource> roleResources = roleResourceMapper.selectByExample(null);
		for(Role role : roles) {
			RoleVO roleVO = new RoleVO();
			roleVO.setId(role.getId());
			roleVO.setName(role.getName());
			roleVO.setRole(role.getRole());
			roleVO.setDescription(role.getDescription());
			List<Long> resIds = new ArrayList<>();
			for(RoleResource roleResource : roleResources) {
				if(roleResource.getRoleId()==role.getId()) {
					resIds.add(roleResource.getResourceId());
				}
			}
			roleVO.setResourceIds(resIds);
			roleVOList.add(roleVO);
		}
		PageHelper.startPage(page, rows);
		return roleVOList;
	}

	@Override
	public void insertRole(RoleVO roleVO) {
		roleMapper.insert(roleVO);
		for(Long resoureId : roleVO.getResourceIds()) {
			RoleResource roleResource = new RoleResource();
			roleResource.setRoleId(roleVO.getId());
			roleResource.setResourceId(resoureId);
			roleResourceMapper.insert(roleResource);
		}
	}

	@Override
	public void updateRole(RoleVO roleVO) {
		roleMapper.updateByPrimaryKeyWithBLOBs(roleVO);
		RoleResourceExample example = new RoleResourceExample();
		Criteria criteria = example.createCriteria();
		criteria.andRoleIdEqualTo(roleVO.getId());
		roleResourceMapper.deleteByExample(example);
		for(Long resoureId : roleVO.getResourceIds()) {
			RoleResource roleResource = new RoleResource();
			roleResource.setRoleId(roleVO.getId());
			roleResource.setResourceId(resoureId);
			roleResourceMapper.insert(roleResource);
		}
	}

	@Override
	public void deleteRoleById(Long id) {
		roleMapper.deleteByPrimaryKey(id);
		RoleResourceExample example = new RoleResourceExample();
		Criteria criteria = example.createCriteria();
		criteria.andRoleIdEqualTo(id);
		roleResourceMapper.deleteByExample(example);
	}

}
